<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use app\common\library\Auth;
use app\admin\model\Car as Car_Model;
use think\Config;
use fast\Http;
/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];
    protected $Car_Model;

    public function _initialize()
    {
        parent::_initialize();
        $this->user_id = $this->auth->id;
        $this->Car_Model = new Car_Model();
        // $this->user_id = 1;
    }  

     /**
     * 商品列表
     * @ApiSummary  ()
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/index/goods_list)
     * @ApiParams   (name="nowpage",type=int,required=true,description="当前页码 ")
     * @ApiReturn ({
       {
  "code": 1,
  "msg": "商品列表",
  "time": "1599555262",
  "data": {
    "sum_page": 5,//总页数
    "list": [
      "id": 1,
      "user_id": 1,
      "name": "测试",
      "price": "1.00",
      //image 是商品列表展示图片，images是商品轮播图
      "image": "http://vicky.jinyu.com/uploads/20200908/a33d9a0ee4da1527267497f192573d1f.jpg",
      "images": "https://weike.bidou88.cn/uploads/20200429/7b7c23769c990da825ee021354985750.jpg,http://vicky.jinyu.com/uploads/20200908/a33d9a0ee4da1527267497f192573d1f.jpg",
      "gearbox": "automatic",//变速箱（手动挡、自动挡）
      "show_mileage": "1",//汽车里程数
      "car_displacement": "1.00",//汽车排量
      "Registration_time": 1598889600,
      "Compulsory_insurance_due_time": 1598889600,
      "Inspection_due_time": 1598889600,
      "color": "black",
      "vehicle_type": "car",//汽车类型（车辆类型:car=轿车,SUV=越野车/SUV,MPV=商务车/MPV,Dual_clutch=双离开,CVT_continuously_variable=CVT无极变速,Seven_speed_dual_clutch=七档双离合）
      "city": "安徽省/芜湖市/弋江区",//发布地区
      "brand_id": 2,
      "country": "china",//国别
      "car_age": "1.00",//车龄
      "phone": "18088888888",
      "content": "11",
      "weigh": 1,
      "status": "1",
      "updatetime": 1599555260,
      "createtime": 1599553892,
      "gearbox_text": "自动",
      "Registration_time_text": "2020-09",
      "Compulsory_insurance_due_time_text": "2020-09",
      "Inspection_due_time_text": "2020-09",
      "Create_Time_text": "2020-09-08 16:31",
      "color_text": "黑色",
      "vehicle_type_text": "轿车",
      "country_text": "国系",
      "status_text": "在售"
    }
  ]
}
     })
     */
    public function goods_list(){
        
        $nowpage = input('nowpage')?input('nowpage'):1;

        $row = $this->Car_Model->where(['status'=>1])->order('weigh desc')->page($nowpage, 10)->select();
        $count = DB::name('car')->where(['status'=>1])->count();
        $this->success('商品列表',['sum_page'=>ceil($count/10),'list'=>$row]);
    }

     /**
     * 搜索商品
     * @param string $name 车源名字
     * @param string $nowpage 当前分页
     * @param string $city 地址区域
     * @param string $vehicle_type 车辆类型:car=轿车,SUV=越野车/SUV,MPV=商务车/MPV,Sports_car=跑车,Pickup=皮卡,van=面包车,Passenger_car=客车,truck=货车,7_seats=7座,Touring_car=房车,open_car=敞篷车,Coupe=轿跑,new_energy=新能源
     * @param string $price 价格。0-50000:5万一下,50000,100000:5万-10万,100000,150000:10万-15万,150000,300000:15万-30万,30w_up:30万以上
     * @param string $car_age 车龄。0,1:0-1年,1,3:1-3年,3,5:3年-5年,5_up:5年以上 
     * @param string $car_displacement 汽车排量 
     * @param string $show_mileage 汽车里程数。0,20000:0-2万公里，20000,50000:2-5万公里，50000,100000:5-10万公里,10w_up:10万公里以上
     * @param string $country 国别:china=国系,german=德系,european=欧系,japanese=日系,france=法系,america=美系,korean=韩系
     * @param string $gearbox 变速箱:manual=手动,automatic=自动,Hand_in_one=手自一体,Dual_clutch=双离开,CVT_continuously_variable=CVT无极变速,Seven_speed_dual_clutch=七档双离合 
     * @param string $color 车身颜色:black=黑色,white=白色,red=红色,blue=蓝色,grey=灰色,green=绿色,yellow=黄色,silver=银色,orange=橙色,golden=金色,purple=紫色,Champagne_gold=香槟金色,brown=棕色,other=其他
     */
    public function search(){
        $param = input();
        $param['status'] = 1;
        $nowpage = input('nowpage')?input('nowpage'):1;
        $price = $param['price'];
        $car_age = $param['car_age'];
        $show_mileage = $param['show_mileage'];
        $name = $param['name'];
        if(!empty($price)){
            if($price=='30w_up'){
                $param['price'] = ['EGT','30'];
            }else{
                $param['price'] = ['between',$price];
            }
        }
        if(!empty($car_age)){
            if($car_age=='5_up'){
                $param['car_age'] = ['EGT','5'];
            }else{
                $param['car_age'] = ['between',$car_age];
            }
        }

        if(!empty($show_mileage)){
            if($show_mileage=='10w_up'){
                $param['show_mileage'] = ['EGT','10'];
            }else{
                $param['show_mileage'] = ['between',$show_mileage];
            }
        }
        if($param['city']){
            $city = $param['city'];
            $param['city'] = ['LIKE',"%$city%"];
        }

        if($name){
            $param['name'] = ['LIKE',"%$name%"];

            $user = $this->auth->getUser();
            if($user->history_name){
                $history_name = explode(',', rtrim($user->history_name,','));

                $key = array_search($name, $history_name);

                if ($key !== false){
                    unset($history_name[$key]);
                }

                array_unshift($history_name, $name);
                $history_string = implode(',', $history_name);

            }else{
                $history_string = $name.',';
            }
            $user->save(['history_name'=>$history_string]);
        }

        $row = $this->Car_Model
        ->where(array_filter($param))
        ->order('weigh desc')
        ->page($nowpage,10)
        ->select();

        $count = $this->Car_Model
        ->where(array_filter($param))
        ->count();
        
        $this->success('搜索商品',['list'=>$row,'sum_page'=>ceil($count/10)]);
    }

     /**
     * 车源分享页面
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/index/share_detail)
     * @ApiParams   (name="goods_id",type=int,required=true,description="商品id")
     * @ApiReturn ({
     })
     */
    public function share_detail(){
        $goods_id = input('goods_id');
        if(empty($goods_id))$this->error('缺少商品id');

        $data['data'] = $this->Car_Model->get($goods_id);
        
        $if_exist = Db::name('goods_qrcode')->where(['user_id'=>$this->user_id,'goods_id'=>$goods_id])->find();

        if($if_exist){
            $data['img'] = $if_exist['image'];
        }else{
        header('content-type:text/html;charset=utf-8');

        $config = get_addon_config('epay');
        
        //配置APPID、APPSECRET
        $APPID = $config['wechat']['miniapp_id']; 
        $APPSECRET = $config['wechat']['app_secret']; 
        //获取access_token
        $access_token = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$APPID&secret=$APPSECRET";

        $ACCESS_TOKEN = Db::name('access_token')->order('expires_in desc')->find();

        if(empty($ACCESS_TOKEN) || time()> $ACCESS_TOKEN['expires_in'])
        {
         $json = Http::sendRequest( $access_token );
         $json = $json['msg'];
         $json = json_decode($json,true);
         $insert_data['access_token'] = $json['access_token'];
         $insert_data['expires_in'] = time()+7200;
         Db::name('access_token')->insert($insert_data);
         $ACCESS_TOKEN =  $ACCESS_TOKEN["access_token"]; 
        } 
        else{
         $ACCESS_TOKEN =  $ACCESS_TOKEN["access_token"]; 
        }
        $name_array = [];
        
        $name = mt_rand(1000,9999).$this->user_id;

        //构建请求二维码参数
        //path是扫描二维码跳转的小程序路径，可以带参数?id=xxx
        //width是二维码宽度
        $qcode ="https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=$ACCESS_TOKEN";

        $path = "pages/index/index?goods_id=$goods_id&user_id=$this->user_id";

        $param = json_encode(array("path"=>$path,"width"=> 150));
        //POST参数
        $result = Http::sendRequest($qcode, $param, 'POST');
        //生成二维码
        $result = $result['msg'];

        $save_path = 'uploads/qrcode/'.$name.'.png';

        file_put_contents($save_path, $result);
        $base64_image ="data:image/jpeg;base64,".base64_encode( $result );



        $name_array['goods_id'] = $goods_id;
        $name_array['user_id'] = $this->user_id;
        $name_array['image'] = Config::get('site.cdnurl').$save_path;

        Db::name('goods_qrcode')->insert($name_array);
        $data['img'] = Config::get('site.cdnurl').$save_path;
        }

        $this->success('车源分享页面',$data);
    }
    /**
    * 分享给新会员
    **/

    public function share_huiyuan(){
        $image = Db::name('share_qrcode')->where('user_id',$this->user_id)->value('image');
        if(!$image){
            $config = get_addon_config('epay');
        
            //配置APPID、APPSECRET
            $APPID = $config['wechat']['miniapp_id']; 
            $APPSECRET = $config['wechat']['app_secret']; 
            //获取access_token
            $access_token = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$APPID&secret=$APPSECRET";

            $ACCESS_TOKEN = Db::name('access_token')->order('expires_in desc')->find();

            if(empty($ACCESS_TOKEN) || time()> $ACCESS_TOKEN['expires_in'])
            {
             $json = Http::sendRequest( $access_token );
             $json = $json['msg'];
             $json = json_decode($json,true);
             $insert_data['access_token'] = $json['access_token'];
             $insert_data['expires_in'] = time()+7200;
             Db::name('access_token')->insert($insert_data);
             $ACCESS_TOKEN =  $ACCESS_TOKEN["access_token"]; 
            } 
            else{
             $ACCESS_TOKEN =  $ACCESS_TOKEN["access_token"]; 
            }
            
            $name = mt_rand(1000,9999).$this->user_id;

            //构建请求二维码参数
            //path是扫描二维码跳转的小程序路径，可以带参数?id=xxx
            //width是二维码宽度
            $qcode ="https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=$ACCESS_TOKEN";

            $path = "pages/index/vehicleDetails?user_id=$this->user_id";

            $param = json_encode(array("path"=>$path,"width"=> 150));
            //POST参数
            $result = Http::sendRequest($qcode, $param, 'POST');
            //生成二维码
            $result = $result['msg'];

            $save_path = 'uploads/shareqrcode/'.$name.'.png';

            file_put_contents($save_path, $result);
            $base64_image ="data:image/jpeg;base64,".base64_encode( $result );

            $name_array['user_id'] = $this->user_id;
            $name_array['image'] = Config::get('site.cdnurl').$save_path;

            Db::name('share_qrcode')->insert($name_array);
            $image = Config::get('site.cdnurl').$save_path;
        }

        $this->success('分享二维码',$image);
        
    }

     /**
     * 商品详情页面
     * @ApiSummary  ()
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/index/goods_detail)
     * @ApiParams   (name="goods_id",type=int,required=true,description="商品id")
     * @ApiReturn ({
     })
     */
    public function goods_detail(){
        $goods_id = input('goods_id');
        if(empty($goods_id))$this->error('缺少商品id');
        
        $data = $this->Car_Model->get($goods_id);

        $user_data = Db::name('user')->where(['id'=>$this->user_id])->field('history,tui_user_id,vip_time')->find();

        $now_time = time();

        if($user_data['vip_time']){
            if($user_data['vip_time']>=$now_time){
                $vip_time_status = 1;
            }else{
                $vip_time_status = 0;
            }
        }else{
            $vip_time_status = 0;
        }

        if(!$vip_time_status){
            $data['phone'] = Db::name('user')->where(['id'=>$user_data['tui_user_id']])->value('mobile');
        }

        if($user_data['history']){
            $history_array = explode(',', $user_data['history']);

            $key = array_search($goods_id, $history_array);

            if ($key !== false){
                unset($history_array[$key]);
            }

            array_unshift($history_array, $goods_id);
            $history_string = implode(',', $history_array);

        }else{
            $history_string = $goods_id.',';
        }
        Db::name('user')->where('id',$this->user_id)->update(['history'=>$history_string]);

        $this->success('商品详情页面',$data);
    }

    /**
    * 历史搜索标题 
    **/
    public function history_name(){
      $user = $this->auth->getUser();
      if($user->history_name){
        $history_name = explode(',', rtrim($user->history_name,','));
      }else{
        $history_name = [];
      }

      $this->success('历史搜索标题',$history_name);
    }

    /**
    * 清空历史搜索标题 
    **/
    public function history_delete(){
      $user = $this->auth->getUser();
      
      Db::name('user')->where(['id'=>$user->id])->update(['history_name'=>'']);

      $this->success('清空历史搜索标题成功');
    }
    /**
    * 获取帮助手册 
    **/
    public function get_help(){
        $this->success('帮助手册',Config('site.manual'));
    }

    /**
    * 获取汽车品牌(键名就是品牌id) 
    **/
    public function get_brand(){
        $brand_data = [];
        $brand = Db::name('brand')->select();
        foreach ($brand as $key => $value) {
            $brand_data[$value['first_letter']][$value['id']] = $value['name'];
        }
        $this->success('获取汽车品牌',$brand_data);
    }

    /**
     * 发布/修改/下架/上架车源
     * @param string $id 修改时候传id过来，时间都传时间戳过来
     * @param string $status 重新上架时候传1，下架时候传3
     * @param string $name 
     * @param string $price 报价
     * @param string $image 展示图片
     * @param string $images 详情里面的轮播图,多个情况下用逗号拼接
     * @param string $gearbox 变速箱:manual=手动,automatic=自动,Hand_in_one=手自一体,Dual_clutch=双离开,CVT_continuously_variable=CVT无极变速,Seven_speed_dual_clutch=七档双离合
     * @param string $show_mileage 表显里程
     * @param string $car_displacement 汽车排量
     * @param string $Registration_time 上牌时间
     * @param string $Compulsory_insurance_due_time 强制保险到期
     * @param string $Inspection_due_time 车检到期
     * @param string $color 车身颜色:black=黑色,white=白色,red=红色,blue=蓝色,grey=灰色,green=绿色,yellow=黄色,silver=银色,orange=橙色,golden=金色,purple=紫色,Champagne_gold=香槟金色,brown=棕色,other=其他
     * @param string $vehicle_type 车辆类型:car=轿车,SUV=越野车/SUV,MPV=商务车/MPV,Sports_car=跑车,Pickup=皮卡,van=面包车,Passenger_car=客车,truck=货车,7_seats=7座,Touring_car=房车,open_car=敞篷车,Coupe=轿跑,new_energy=新能源
     * @param string $city 车辆位置所在城市
     * @param string $brand_id 汽车品牌
     * @param string $country 国别:china=国系,german=德系,european=欧系,japanese=日系,france=法系,america=美系,korean=韩系
     * @param string $car_age 车龄
     * @param string $phone
     * @param string $content
     */
    public function post_car(){
        $params = input();
        $params['user_id'] = $this->user_id;

        if($params['id']){

            $res = $this->Car_Model->isUpdate(true)->save(array_filter($params));
        }else{
            unset($params['id']);
            $res = $this->Car_Model->save($params);
        }
        if($res){
            $this->success('操作成功');
        }
    }





}
